<script setup lang="ts">
import { computed, onMounted, ref, VNode } from "vue";
import type { SRPage } from "@/api/response";

const props = defineProps<{
  load: (SRPage) => Promise<{ list: any[]; total: number }>;
  query?: any;
}>();

const loading = ref(false);
const noMore = ref(false);
const disabled = computed(() => loading.value || noMore.value);
const data = ref([]);

const tableRef = ref();

const query = ref({
  pageNum: 1,
  pageSize: 10,
  ...props.query
});

const loadMore = async () => {
  if (disabled.value) {
    return;
  }
  loading.value = true;
  const res = await props.load(query.value);
  loading.value = false;
  data.value.push(...res.list);
  if (res.list.length < query.value.pageSize) {
    noMore.value = true;
  } else {
    query.value.pageNum++;
  }
};

const reload = async () => {
  query.value.pageNum = 1;
  loading.value = false;
  noMore.value = false;
  data.value = [];
  await loadMore();
};

onMounted(() => {
  reload();
});

defineExpose({
  reload
});
</script>

<template>
  <el-table
    ref="tableRef"
    v-el-table-infinite-scroll="loadMore"
    :infinite-scroll-disabled="disabled"
    class="rollTableRow"
    :data="data"
    :loading="loading"
    v-bind:="$attrs"
  >
    <slot />
  </el-table>
</template>
<style lang="scss" scoped>
.rollTableRow {
  height: 100%;
}
</style>
